#!/usr/bin/env bash

## 下载软件
cd ~
dnf install -y tar wget
wget https://github.com/etcd-io/etcd/releases/download/v3.5.4/etcd-v3.5.4-linux-amd64.tar.gz
mkdir /opt/etcd/{bin,cfg,ssl} -pv
tar xf etcd-v3.5.4-linux-amd64.tar.gz
mv etcd-v3.5.4-linux-amd64/{etcd,etcdctl} /opt/etcd/bin/

## 创建 etcd 配置
cat > /opt/etcd/cfg/etcd.conf << EOF
#[Member]
ETCD_NAME="${ETCD_CURRENT_NODE_HOSTNAME}"
ETCD_DATA_DIR="/var/lib/etcd/default.etcd"
ETCD_LISTEN_PEER_URLS="https://${ETCD_CURRENT_NODE_IP}:2380"
ETCD_LISTEN_CLIENT_URLS="https://${ETCD_CURRENT_NODE_IP}:2379"
#[Clustering]
ETCD_INITIAL_ADVERTISE_PEER_URLS="https://${ETCD_CURRENT_NODE_IP}:2380"
ETCD_ADVERTISE_CLIENT_URLS="https://${ETCD_CURRENT_NODE_IP}:2379"
ETCD_INITIAL_CLUSTER="${ETCD_NODE1_HOSTNAME}=https://${ETCD_NODE1_IP}:2380,${ETCD_NODE2_HOSTNAME}=https://${ETCD_NODE2_IP}:2380,${ETCD_NODE3_HOSTNAME}=https://${ETCD_NODE3_IP}:2380"
ETCD_INITIAL_CLUSTER_TOKEN="etcd-cluster"
ETCD_INITIAL_CLUSTER_STATE="new"
EOF

## 创建 etcd 服务
cat > /usr/lib/systemd/system/etcd.service << EOF
[Unit]
Description=Etcd Server
After=network.target
After=network-online.target
Wants=network-online.target
[Service]
Type=notify
EnvironmentFile=/opt/etcd/cfg/etcd.conf
ExecStart=/opt/etcd/bin/etcd \
--cert-file=/opt/etcd/ssl/server.pem \
--key-file=/opt/etcd/ssl/server-key.pem \
--peer-cert-file=/opt/etcd/ssl/server.pem \
--peer-key-file=/opt/etcd/ssl/server-key.pem \
--trusted-ca-file=/opt/etcd/ssl/ca.pem \
--peer-trusted-ca-file=/opt/etcd/ssl/ca.pem \
--logger=zap
Restart=on-failure
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
EOF

## 拷贝证书
cp ~/TLS/etcd/ca*pem ~/TLS/etcd/server*pem /opt/etcd/ssl/

echo "----------- Etcd status----------"
systemctl status etcd